export const getDataType = (data) => {
  const temp = Object.prototype.toString.call(data);
  const type = temp.match(/\b\w+\b/g);
  return type.length < 2 ? "Undefined" : type[1];
};

// 浅比较，一层比较
export const isObjectChanged = (source, comparison) => {
  const _source = JSON.stringify(source);
  const _comparison = JSON.stringify({ ...source, ...comparison });
  return _source !== _comparison;
};

// 深比较
export const deepCompare = (source, comparison) => {
  const iterable = (data) => ["Object", "Array"].includes(getDataType(data));
  if (!iterable(source)) {
    throw new Error(
      `source should be a Object or Array , but got ${getDataType(source)}`
    );
  }
  if (getDataType(source) !== getDataType(comparison)) {
    return true;
  }
  const sourceKeys = Object.keys(source);

  const comparisonKeys = Object.keys({ ...source, ...comparison });

  // 因为有undefined的存在 length有问题
  // if (sourceKeys.length !== comparisonKeys.length) {
  //   return true;
  // }

  return comparisonKeys.some((key) => {
    if (iterable(source[key])) {
      return deepCompare(source[key], comparison[key]);
    } else {
      return source[key] !== comparison[key];
    }
  });
};

export const deepClone = (origin) => {
  if (origin === undefined) {
    return undefined;
  }
  return JSON.parse(JSON.stringify(origin));
};
